<template>
  <div class="scroll-wrapper">
    <van-pull-refresh v-model="pullLoading" @refresh="onRefresh">
      <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
        <van-cell v-for="(item,idx) in list" :key="idx" :title="item.title">
          <div slot="label">
            <!-- 图片 当前文章有几张图 就用几个宫格 -->
            <van-grid :column-num="item.cover.images.length">
              <van-grid-item v-for="(img,idx) in item.cover.images" :key="idx">
                <van-image lazy-load :src="img" />
              </van-grid-item>
            </van-grid>

            <!-- 文字说明 -->
            <div class="meta">
              <span>{{item.aut_name}}</span>
              <span>{{item.comm_count}}评论</span>
              <span>{{item.pubdate | relativeTime}}</span>
              <span
              class="close"
              v-if="$store.state.tokenInfo.token"
              @click="hClose(item)">
                <van-icon name="cross"></van-icon>
              </span>
            </div>
          </div>
        </van-cell>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArticles } from '@/api/article.js';
export default {
  name: 'ArticleList',
  props: ['channel'],
  data () {
    return {
      list: [],
      timestamp: null,
      loading: false,
      finished: false,
      pullLoading: false
    };
  },
  created () {
    this.$eventBus.$on('delArticle', obj => {
      if (obj.channelId !== this.channel.id) {
        console.log('与我无关')
        return
      }
      const idx = this.list.findIndex(item => item.art_id.toString() === obj.articleId)
      if (idx !== -1) {
        this.list.splice(idx, 1)
      }
    })
  },
  methods: {
    hClose (article) {
      this.$emit('showMoreActive', article.art_id.toString())
    },
    async onRefresh () {
      const res = await getArticles(this.channel.id, Date.now());
      console.log(res)
      const arr = res.data.data.results
      this.list = arr.concat(this.list)
      this.$toast.success('刷新成功' + arr.length + '条')
      this.pullLoading = false
    },
    async onLoad () {
      if (!this.timestamp) {
        this.timestamp = Date.now();
      }
      // 异步更新数据
      const res = await getArticles(this.channel.id, this.timestamp);
      this.timestamp = res.data.data.pre_timestamp;
      const arr = res.data.data.results;
      this.list = this.list.concat(arr);
      this.loading = false;
      if (arr.length === 0) {
        this.finished = true;
      }
    }
  }
};
</script>

<style scoped lang='less'>
.meta {
  display: flex;
  span {
    margin-right: 10px;
  }
  .close {
    margin-left: auto;
  }
}
</style>
